﻿using Microsoft.AspNetCore.Mvc;
using Single.AppCore;
using Single.Core.Service;
using Single.Logger;
using Single.Utils;
using Single.WebApp.Components;
using Single.YitId;
using System.Globalization;

namespace Single.WebApp.Areas.Other
{
    [Area("other")]
    public class UploadController : WorkController
    {
        public string Cut(string dir, int width, int height)
        {
            var temp = $"{GlobalApp.RootPath}/wwwroot/userfiles/temp/";
            var path = $"{GlobalApp.RootPath}/wwwroot/userfiles/{dir}/";

            if (!Directory.Exists(temp)) { Directory.CreateDirectory(temp); }
            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

            if (Request.Form.Files.Count > 0)
            {
                try
                {
                    IFormFile file = Request.Form.Files[0];
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    string tempFile = $"{temp}{Guid.NewGuid()}{fileExt}";
                    string fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}_{YitIdHelper.NextId()}{fileExt}";

                    using (var fs = new FileStream(tempFile, FileMode.Create))
                    {
                        file.CopyTo(fs);
                    }

                    ThumbnailHelper.Generate(tempFile, path + fileName, width, height, TnType.Cut);

                    System.IO.File.Delete(tempFile);

                    return ServiceResult.SerializeData(data: new { file = fileName });
                }
                catch (Exception ex)
                {
                    LoggerHelper.Error(ex.Message, ex); throw ex;
                }
            }
            else { throw new Exception("未找到文件！"); }
        }

        public string File(string dir)
        {
            var path = $"{GlobalApp.RootPath}/wwwroot/userfiles/{dir}/";

            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

            if (Request.Form.Files.Count > 0)
            {
                try
                {
                    IFormFile file = Request.Form.Files[0];
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    string fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}_{YitIdHelper.NextId()}{fileExt}";

                    using (var fs = new FileStream(path + fileName, FileMode.Create))
                    {
                        file.CopyTo(fs);
                    }

                    return ServiceResult.SerializeData(data: new { text = file.FileName, file = fileName });
                }
                catch (Exception ex)
                {
                    LoggerHelper.Error(ex.Message, ex); throw ex;
                }
            }
            else { throw new Exception("未找到文件！"); }
        }
    }
}